package com.enlorenz.common.security.rsa;

import java.security.KeyPair;

import com.enlorenz.common.util.CommonContants;
import com.enlorenz.common.util.StringUtils;

public abstract class AbstractRSA {
	public static final String CHAR_SET=CommonContants.UTF_8_CHARSET;
	protected abstract String bytes2String(byte [] data);
	protected abstract byte [] string2Bytes(String data);
	
	/**
	 * 用私钥对信息生成数字签名
	 * 
	 * @param data 加密数据
	 * @param privateKey 私钥
	 * @return
	 * @throws Exception
	 */
	public String sign(String data, String key){
		return bytes2String(BaseRSAUtils.sign(string2Bytes(data), string2Bytes(key)));
	}

	/**
	 * 校验数字签名
	 * 
	 * @param data 加密数据
	 * @param publicKey 公钥
	 * @param sign 数字签名
	 * 
	 * @return 校验成功返回true 失败返回false
	 * @throws Exception
	 * 
	 */
	public boolean verify(String data, String key, String sign){
		// 验证签名是否正常
		return BaseRSAUtils.verify(string2Bytes(data), string2Bytes(key),string2Bytes(sign));
	}

	/**
	 * 解密<br>
	 * 用私钥解密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public String decryptByPrivateKey(String data, String key){
		byte [] buff=BaseRSAUtils.decryptByPrivateKey(string2Bytes(data), string2Bytes(key));
		return StringUtils.newString(buff,CHAR_SET);
	}

	/**
	 * 解密<br>
	 * 用公钥解密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public String decryptByPublicKey(String data, String key){
		byte [] buff=BaseRSAUtils.decryptByPublicKey(string2Bytes(data), string2Bytes(key));
		return StringUtils.newString(buff,CHAR_SET);
	}
	
	
	/**
	 * 加密<br>
	 * 用公钥加密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public String encryptByPublicKey(String data,String key){
		byte [] result=BaseRSAUtils.encryptByPublicKey(StringUtils.getBytes(data,CHAR_SET), string2Bytes(key));
		return bytes2String(result);
	}

	/**
	 * 加密<br>
	 * 用私钥加密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public String encryptByPrivateKey(String data,String key){
		byte [] result=BaseRSAUtils.encryptByPrivateKey(StringUtils.getBytes(data,CHAR_SET), string2Bytes(key));
		return bytes2String(result);
	}


	/**
	 * 初始化密钥
	 * @return
	 * @throws Exception
	 */
	public RSAKeyObject initKey(){
		KeyPair keyPair = BaseRSAUtils.initKey();
		String publicKey = bytes2String(BaseRSAUtils.getPublicKey(keyPair));
		String privateKey = bytes2String(BaseRSAUtils.getPrivateKey(keyPair));
		return new RSAKeyObject(publicKey,privateKey);
	}
	
	public static class RSAKeyObject{
		private String publicKey;
		private String privateKey;
		
		public RSAKeyObject(String publicKey, String privateKey) {
			super();
			this.publicKey = publicKey;
			this.privateKey = privateKey;
		}
		public String getPublicKey() {
			return publicKey;
		}
		public void setPublicKey(String publicKey) {
			this.publicKey = publicKey;
		}
		public String getPrivateKey() {
			return privateKey;
		}
		public void setPrivateKey(String privateKey) {
			this.privateKey = privateKey;
		}
	}
}
